{% load static %}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>...</title>
  <!-- 请勿在项目正式环境中引用该 layui.css 地址 -->
  <!-- <link href="//unpkg.com/layui@2.9.23/dist/css/layui.css" rel="stylesheet"> -->
  <link rel="stylesheet" href="{% static 'layui/css/layui.css' %}">
</head>
<body>

<div class="layui" style="margin:20px">

	<form class="layui-form" style="margin-bottom: 20px">
		<div class="layui-form-item">
		 <label class="layui-form-label" style="width: 100px">请输入名称</label>
	    <div class="layui-input-inline">
	     <input type="text" name="name" value="" placeholder="请输入名称" class="layui-input" lay-affix="clear">
	    </div>

		<label class="layui-form-label" style="width: 100px">请输入密码</label>
		<div class="layui-input-inline">
		  <input type="text" name="password" placeholder="请输入密码" lay-affix="clear" class="layui-input">
		</div>

		<label class="layui-form-label" style="width: 100px">请输入年龄</label>
		<div class="layui-input-inline">
		  <input type="text" name="age" placeholder="请输入年龄" lay-affix="clear" class="layui-input">
		</div>

		<button class="layui-btn" lay-submit lay-filter="search">搜索</button>
		<button type="reset" class="layui-btn layui-btn-primary">清空</button>


	  </div>



	  <div class="layui-form-item">
		  <label class="layui-form-label" style="width: 100px">请选择部门</label>
		  <div class="layui-input-inline">
		    <div id="bId"  class="xm-select-demo"></div>
		  </div>



	  </div>

	</form>

	<table class="layui-hide" id="ID-table-demo-data" lay-filter='test'></table>
</div>

<script src="{% static 'layui/layui.js' %}"></script>
<script src="{% static 'js/xm-select.js' %}"></script>

<script>
	layui.use('table',function(){
		let table = layui.table;
		let $ = layui.$;
		let layer = layui.layer;
		let form = layui.form;


		//搜索
		 form.on('submit(search)', function(data){
		    var field = data.field; // 获得表单字段
			console.log(field);
		    // 执行搜索重载
		    table.reload('ID-table-demo-data', {
		      page: {
		        curr: 1 // 重新从第 1 页开始
		      },
		      where: field // 搜索的字段
		    });
		    // layer.msg('搜索成功<br>此处为静态模拟数据，实际使用时换成真实接口即可');
		    return false; // 阻止默认 form 跳转
		  });
		// });

		//xm-sleect下拉框
		let demo1 = xmSelect.render({
			el: '#bId',
			filterable: true,
			radio: true,
			name:"department",
			data: [
				{name: '运营部', value: 1},
				{name: '企划部', value: 2},
				{name: 'it部', value: 3},
				{name: '人事部', value: 4},
				{name: '财务部', value: 5},
				{name: '销售部', value: 6}
			]
		})

		//头部工具栏事件
		table.on('toolbar(test)',function(obj){
			// console.log(obj)
			// console.log('顶部工具栏被触发',obj);
			let event = obj.event;
			if(event=='add'){
				//添加时间
				// layer.msg('要新增数据拉', {offset: '50px'})
				console.log('添加数据');
				layer.open({
					title:'添加人员',
					type:2,
					content:"add.html",
					area:['500px','600px'],
					anim:1,
					end: function(){
						table.reload('ID-table-demo-data')
					    console.log('弹层已被移除');
					  }
				});
			}else if(event=='batcDel'){
				//批量删除

				let id = obj.config.id;
				let checkStatus = table.checkStatus(id)
				let list = checkStatus.data
				if(list && list.length==0){
					layer.msg('没有选择要删除的数据');
				}else{
					layer.confirm('确定是否删除？',{icon: 3, title:'警告',btn:['确定','取消']},function(index){
						console.log(list);

						//构建参数
						let arr = [];

						for(let i=0;i<list.length;i++){
							console.log(list)
							arr.push(list[i].id)
						}
						console.log(arr);

						//ajax调用
						$.ajax({
							url:'http://127.0.0.1:8000/user/batc-delete/',
							type:'DELETE',
							headers: {
								'Content-Type': 'application/json',
								// 如果需要身份验证，可以在这里添加认证头
								//'Authorization': 'Bearer your-token-if-needed'
							},
							data:JSON.stringify({"ids": arr}),

							success: function(result) {
								if(result.code===0){
									console.log("删除成功:", result);
									table.reload('ID-table-demo-data')
								}else{
									layer.msg(result.msg)
								}

							},
							error: function(xhr, status, error) {
								console.error("删除失败:", status, error);
							}
						})

						//关闭弹出层
						layer.close(index);
					})
				}

			}else if(event=='refresh'){
				table.reload('ID-table-demo-data')
				// layer.msg('表格刷新了')
			}
		});

		//单元格事件处理
		table.on('tool(test)',function(obj){
			let event = obj.event;
			if(event=='del'){
				layer.confirm('确定删除?',{icon: 3, title:'警告',btn:['确定','取消']},function(index){
					//点击确定
					//删除
					let id = obj.data.id;
					// console.log(id)
					//AXAJ调用
					$.ajax({
						url:'http://127.0.0.1:8000/user/'+id+'/',
						type:'DELETE',
						headers: {
							'Content-Type': 'application/json',
							// 如果需要身份验证，可以在这里添加认证头
							//'Authorization': 'Bearer your-token-if-needed'
						},
						success: function(result) {
							if(result.code===0){
								// console.log("删除成功:", result);
								table.reload('ID-table-demo-data')
							}else{
								layer.msg(result.msg)
							}
						},
						error: function(xhr, status, error) {
							console.error("删除失败:", status, error);
						}
					})
					//关闭弹出层
					layer.close(index);

				})


			}else if(event=='edit'){
				//编辑
				layer.open({
					title:'编辑人员',
					type:2,
					content:"edit.html",
					area:['500px','600px'],
					anim:1,
					end: function(){
						table.reload('ID-table-demo-data')
					    console.log('弹层已被移除');
					  },
					 success: function(layero, index, that){
					    // 弹层的最外层元素的 jQuery 对象
					    console.log(layero);
					    // 弹层的索引值
					    console.log(index);
					    // 弹层内部原型链中的 this --- 2.8+
					    console.log(that);

						let body = layer.getChildFrame('body', index);
						    // 给 iframe 页中的某个输入框赋值
						body.find('#userId').val(obj.data.id);
						body.find('#name').val(obj.data.name);
						body.find('#password').val(obj.data.password);
						body.find('#age').val(obj.data.age);
						// body.find('#department').val(obj.data.department);
					  }
				});
			}else{
				//错误
			}
		});



		// 已知数据渲染
		var inst = table.render({
			elem: '#ID-table-demo-data',
			url:'http://127.0.0.1:8000/user/',
			// headers: {cookie: 'theme=; theme_name=; fold=false; theme=; theme_name=; csrftoken=WdVFE1725x2tDFwnPzXVQIRMAtomYd0j; sessionid=gn6y4fepvlphfd0l7ma9ma2ysxxzq2py'},
			even:true,
			// skin:'line',
			totalRow: false, // 开启合计行
			// page:true,
			page: {
				  limit:5,
				  limits:[5,10,15,20,200]
				},
			request:{
			  pageName:"page",
			  limitName:"page_size"
			},
			parseData: function(res){
				// console.log(res);
				return {
					"code": res.code, // 解析接口状态
					"msg": res.msg, // 解析提示文本
					"count": res.data.count, // 解析数据长度
					"data": res.data.results // 解析数据列表
				  }
			},
			toolbar:`
				<div>
					<button type="button" lay-event="batcDel" class="layui-btn layui-btn-sm layui-bg-red">批量删除</button>
					<button type="button" lay-event="add" class="layui-btn layui-btn-sm layui-btn-normal">新增</button>
					<button type="button" lay-event="refresh" class="layui-btn layui-btn-sm"><i class="layui-icon layui-icon-refresh"></i> </button>
				</div>
			`,

			cols:[[
				 {type: 'checkbox', fixed: 'left'},
					{
						title:'编号',
						field:"id",
						align: 'center'
					},
					{
						title:'姓名',
						field:"name",
						align: 'center'
					},
					{
						title:'密码',
						field:"password",
						align: 'center'
					},
					{
						title:'年龄',
						field:"age",
						sort:true,
						align: 'center'
					},
					{
						title:'部门',
						field:"department_txt",
						align: 'center'
						// templet:function(d){
						// 	console.log(d);
						// 	return d.department.name
						// }
					},
					{
						title:'操作',
						templet:function(d){
							let sy = `
								  <button type="button" lay-event='edit' class="layui-btn layui-btn-xs layui-btn-normal">修改</button>
								  <button type="button" lay-event='del' class="layui-btn layui-btn-xs layui-bg-red">删除</button>
								`
							return sy;
						},
						align: 'center'
					},
			]]
		})

	})
</script>
</body>
</html>